package com.delete;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Properties;

import org.apache.commons.lang3.StringUtils;

public class PropertiesInfo {
	private static volatile PropertiesInfo instance;
	private PropertiesInfo(){}
	public static PropertiesInfo getInstance(){
		if(instance == null){
			synchronized(PropertiesInfo.class){
				if(instance == null){
					instance = new PropertiesInfo();
				}
			}
		}
		return instance;
	}
		
	private final String propFile = "dbinfo.properties";
	private static Properties props = null;
	private ArrayList<String> keys = null;
	
	private String defaultConn;

	private void loadPropsFile(){
		if(props != null) return;
		InputStream propsInfo = this.getClass().getClassLoader().getResourceAsStream(propFile);
		try {
			props.load(propsInfo);
		} catch (IOException e) {					
			e.printStackTrace();
		}
	}
	
	public String getDefaultConn() {
		if(StringUtils.isEmpty(defaultConn)){
			defaultConn = "Conn";
			if(props == null){
				loadPropsFile();
			}
			boolean hasDefaultConn = false;
			String newConn = null;
			if(keys == null){
				Enumeration<?> pNames = props.propertyNames();
		        while(pNames.hasMoreElements()) {
		            String key = (String)pNames.nextElement();
		            int index = key.indexOf('.');
		            String pre = key.substring(0, index);
		            if(StringUtils.isEmpty(pre)) continue;
		            if(pre == defaultConn){
		            	hasDefaultConn = true;
		            }else{
		            	if(newConn == null){
		            		newConn = pre;
		            	}
		            }
		            keys.add(key);
		        }
			}else{
				hasDefaultConn = keys.contains(defaultConn);
				if(!hasDefaultConn){
					for(String key : keys){
						int index = key.indexOf('.');
			            String pre = key.substring(0, index);
		            	if(newConn == null && StringUtils.isNotEmpty(pre)){
		            		newConn = pre;
		            		break;
		            	}
					}
				}				
			}
			if(!hasDefaultConn){
				defaultConn = newConn;
			}
		}
		return defaultConn;
	}

	public void setDefaultConn(String defaultConn) {
		if(defaultConn == null){
			this.defaultConn = StringUtils.EMPTY;
		}else{
			this.defaultConn = defaultConn;
		}
	}
	
}
